package com.ft.turorial.spring.boot.security.servlet;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ft.turorial.spring.boot.security.SecurityConstants;
import com.ft.turorial.spring.boot.security.util.CaptchaUtil;

/**
* @ClassName: CaptchaServlet
* @Description: 生成验证码Servlet
* 【补充说明：
* 		如果采用继承OncePerRequestFilter的方式实现filter,在注意配置时，需要配置在Shiro之后，
* 		因为Shiro将包装HttpSession,否则两次的session id 不一样
*  】
* @author Johnny
*/
@WebServlet(urlPatterns = "/login/captcha")
public class CaptchaServlet extends HttpServlet {

	private static final long serialVersionUID = 1521124570996995824L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置页面不缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setDateHeader("Expires", 0);
		// 设置输出的内容的类型为JPEG图像
		response.setContentType("image/jpeg");
		// 生产验证码
		String captcha = CaptchaUtil.generateTextCode(CaptchaUtil.TYPE_NUM_ONLY, 4, null);
		// 将生成的验证码放到HttpSession里面（对应session的ID也写入进去，用于验证验证码）【SecurityUtils.getSubject().getSession()
		// 与 request.getSession() 是同一个session】
		request.getSession().removeAttribute(SecurityConstants.SESSION_KEY_CAPTCHA);
		request.getSession().setAttribute(SecurityConstants.SESSION_KEY_CAPTCHA, captcha);
		request.getSession().setAttribute(SecurityConstants.SESSION_KEY_ID, request.getSession().getId());
		System.out.println("【本次生成验证码：" + captcha + "】已存入HttpSession中【SessionId=" + request.getSession().getId() + "】");

		BufferedImage bufferedImage = CaptchaUtil.generateImageCode(captcha, 90, 32, 8, true, Color.WHITE, Color.BLACK, null);
		// 写给浏览器
		ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
		try {
			response.getOutputStream().flush();
		} finally {
			response.getOutputStream().close();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
